package com.example.nutritionmanager.ocr

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.material3.MaterialTheme
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import com.example.nutritionmanager.R
import com.yalantis.ucrop.UCrop
import dagger.hilt.android.AndroidEntryPoint
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

@AndroidEntryPoint
class CameraActivity : AppCompatActivity() {

    private lateinit var imageView: ImageView
    private lateinit var captureButton: Button
    private lateinit var galleryButton: Button
    private lateinit var previewView: PreviewView
    private lateinit var cameraExecutor: ExecutorService

    private val captureImageRequestCode = 1001
    private val pickImageRequestCode = 1002
    private val cropImageRequestCode = 1003
    private lateinit var imageCapture: ImageCapture

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera)
        // 获取 Toolbar 并设置
        val toolbar: Toolbar = findViewById(R.id.toolbarCamera)
        setSupportActionBar(toolbar)

        // 设置返回按钮
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_arrow_back_white)

        // 处理返回按钮的点击事件
        toolbar.setNavigationOnClickListener {
            onBackPressed()  // 返回上一个页面
        }

        imageView = findViewById(R.id.imageView)
        captureButton = findViewById(R.id.captureButton)
        galleryButton = findViewById(R.id.galleryButton)
        previewView = findViewById(R.id.previewView)  // 获取 PreviewView 用于显示实时预览

        cameraExecutor = Executors.newSingleThreadExecutor()

        captureButton.setOnClickListener {
            scan()
        }

        galleryButton.setOnClickListener {
            openGallery()
        }

        // 启动相机预览
        startCamera()
    }

    private fun startCamera() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)

        cameraProviderFuture.addListener({
            // 使用 CameraProvider 绑定相机生命周期
            val cameraProvider = cameraProviderFuture.get()

            val preview = Preview.Builder()
                .build()

            preview.setSurfaceProvider(previewView.surfaceProvider)  // 设置预览视图

            val cameraSelector = CameraSelector.Builder()
                .requireLensFacing(CameraSelector.LENS_FACING_BACK) // 选择后置摄像头
                .build()
            imageCapture = ImageCapture.Builder().build()
            try {
                cameraProvider.unbindAll() // 解绑所有已绑定的用例
                cameraProvider.bindToLifecycle(
                    this, cameraSelector, preview, imageCapture
                )
                preview.setSurfaceProvider(previewView.surfaceProvider)
            } catch (e: Exception) {
                Toast.makeText(this, "相机初始化失败", Toast.LENGTH_SHORT).show()
            }
        }, ContextCompat.getMainExecutor(this))
    }

    private fun createImageFile(): File {
        val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(System.currentTimeMillis())
        val storageDir = cacheDir  // 可选: getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File(storageDir, "IMG_$timestamp.jpg")
    }

    private fun openGallery() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, pickImageRequestCode)
    }

    private fun startCrop(sourceUri: Uri) {
        val destinationFileName = "cropped_${System.currentTimeMillis()}.jpg"
        val destinationUri = Uri.fromFile(File(cacheDir, destinationFileName))

        UCrop.of(sourceUri, destinationUri)
            .withAspectRatio(0f, 0f)  // 设置为0表示自由比例
            .withMaxResultSize(1080, 1080)  // 设置最大输出尺寸
            .withOptions(UCrop.Options().apply {
                setHideBottomControls(false)  // 显示底部控制栏
                setShowCropGrid(true)  // 显示裁切网格
                setShowCropFrame(true)  // 显示裁切框
                setFreeStyleCropEnabled(true)  // 启用自由裁切
                setStatusBarColor(ContextCompat.getColor(this@CameraActivity, R.color.white))
                setToolbarTitle("调整图片")
                setToolbarColor(ContextCompat.getColor(this@CameraActivity, R.color.white))
                setActiveControlsWidgetColor(ContextCompat.getColor(this@CameraActivity, R.color.white))
//                setActiveWidgetColor()    
            })
            .start(this)
    }

    private fun scan() {
        val photoFile = createImageFile()
        val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()

        imageCapture.takePicture(
            outputOptions,
            ContextCompat.getMainExecutor(this),
            object : ImageCapture.OnImageSavedCallback {
                override fun onError(exception: ImageCaptureException) {
                    Toast.makeText(this@CameraActivity, "拍照失败: ${exception.message}", Toast.LENGTH_SHORT).show()
                }

                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    val savedUri = FileProvider.getUriForFile(
                        this@CameraActivity,
                        "${packageName}.fileprovider",
                        photoFile
                    )
                    startCrop(savedUri)
                }
            }
        )
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
            val resultUri = UCrop.getOutput(data!!)
            // 跳转到OCR结果界面，并将裁切后的图片URI传递过去
            val intent = Intent(this, OCRResultActivity::class.java)
            intent.putExtra("imageUri", resultUri.toString())
            startActivity(intent)
        } else if (requestCode == pickImageRequestCode && resultCode == RESULT_OK) {
            val selectedImageUri: Uri? = data?.data
            if (selectedImageUri != null) {
                startCrop(selectedImageUri)
            }
        }
    }

    private fun createImageUri(): Uri {
        // 创建用于保存照片的 URI
        val contentValues = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, "captured_image.jpg")
            put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
            put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/CameraApp")
        }
        val uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
        return uri ?: throw IllegalArgumentException("无法创建图片 URI")
    }

    override fun onDestroy() {
        super.onDestroy()
        cameraExecutor.shutdown()  // 关闭执行器
    }
}
